package com.wll.ec.fast.main.cart;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.ViewStubCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.joanzapata.iconify.widget.IconTextView;
import com.wll.ec.core.delegates.bottom.BottomItemDelegate;
import com.wll.ec.core.net.RestClient;
import com.wll.ec.core.net.callback.ISuccess;
import com.wll.ec.core.ui.recycler.MultipleItemEntity;
import com.wll.ec.fast.R;
import com.wll.ec.fast.R2;
import com.wll.ec.fast.pay.FastPay;
import com.wll.ec.fast.pay.IAlPayResultListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by detachment on 2020/3/22
 */
public class ShopCartDelegate extends BottomItemDelegate implements ISuccess, ICartItemListener, IAlPayResultListener {

    private ShopCartAdapter mAdapter = null;
    //购物车数量标记
    private int mCurrentCount = 0;
    private int mTotalCount = 0;
    private double mTotalPrice = 0.00;
    private View stubView = null;

    @BindView(R2.id.rv_shop_cart)
    RecyclerView mRecyclerView = null;
    @BindView(R2.id.icon_shop_cart_select_all)
    IconTextView mIconSelectAll = null;
    @BindView(R2.id.stub_no_item)
    ViewStubCompat mStubNoItem = null;
    @BindView(R2.id.tv_shop_cart_total_price)
    AppCompatTextView mTvTotalPrice = null;

//    @OnClick(R2.id.tv_stub_to_buy)
//    void onClickToBuy() {
//        Toast.makeText(getContext(), "你该购物啦！", Toast.LENGTH_SHORT).show();
//    }

    @OnClick(R2.id.icon_shop_cart_select_all)
    void onClickSelectAll() {
//        int tag = updateViewCheckBtnAllChecked();
        boolean isSelectedAll = mAdapter.getIsSelectedAll();
        if (isSelectedAll){
            mIconSelectAll.setTextColor(Color.GRAY);
        } else {
            mIconSelectAll.setTextColor(ContextCompat.getColor(getContext(), R.color.app_main));
        }
        mAdapter.setIsSelectedAll(!isSelectedAll);
//        mAdapter.notifyDataSetChanged();
        //更新RecyclerView的显示状态
//        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount(), "checkBtn");
        mAdapter.updateAllSelected(!isSelectedAll);
//            EcLogger.d("1233 notifyItemRangeChanged mAdapter.getData()" , String.valueOf(mAdapter.getData()));
    }

    int updateViewCheckBtnAllChecked() {
        final int tag = (int) mIconSelectAll.getTag();
        if (tag == 0) {
            mIconSelectAll.setTextColor(ContextCompat.getColor(getContext(), R.color.app_main));
            mIconSelectAll.setTag(1);
        } else {
            mIconSelectAll.setTextColor(Color.GRAY);
            mIconSelectAll.setTag(0);
        }
        return (int) mIconSelectAll.getTag();
    }

    @OnClick(R2.id.tv_top_shop_cart_remove_selected)
    void onClickRemoveSelectedItem() {
        double subPrice = 0;
        final List<MultipleItemEntity> data = mAdapter.getData();
        //要删除的数据
        final List<MultipleItemEntity> deleteEntities = new ArrayList<>();
        for (MultipleItemEntity entity : data) {
            final boolean isSelected = entity.getField(ShopCartItemFields.IS_SELECTED);
            if (isSelected) {
                deleteEntities.add(entity);
                subPrice = subPrice + ((double) entity.getField(ShopCartItemFields.PRICE)) *
                        (int) entity.getField(ShopCartItemFields.COUNT);
            }
        }
        int size = deleteEntities.size();
        int entityPosition = 0;
        for (int i = size - 1; i >= 0; i--) {
            entityPosition = deleteEntities.get(i).getField(ShopCartItemFields.POSITION);
//            EcLogger.d("1233 entityPosition" , String.valueOf(entityPosition));
//            EcLogger.d("1233 mAdapter.getItemCount()" , String.valueOf(mAdapter.getItemCount()));
            if (entityPosition < mAdapter.getItemCount()) {
//                mAdapter.getData().remove(entityPosition);
                mAdapter.remove(entityPosition);
            }
        }
        mAdapter.updateItemRangeFieldPosition(entityPosition);
//        mAdapter.notifyItemRangeRemoved(entityPosition, mAdapter.getItemCount() - entityPosition);
        //更新数据
//        mAdapter.notifyItemRangeChanged(entityPosition, mAdapter.getItemCount() - entityPosition,"checkBtn");
//        EcLogger.d("1233 notifyItemRangeChanged mAdapter.getData()" , String.valueOf(mAdapter.getData()));

        updateTotalPrice(subPrice);
        checkItemCount();
    }

    @OnClick(R2.id.tv_top_shop_cart_clear)
    void onClickClear() {
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
        updateTotalPrice(mAdapter.getTotalPrice());
        checkItemCount();
    }

    @OnClick(R2.id.tv_shop_cart_pay)
    void onClickPay() {
        createOrder();
    }

    //创建订单，注意，和支付是没有关系的
    private void createOrder() {
        FastPay.create(ShopCartDelegate.this)
                .setPayResultListener(ShopCartDelegate.this)
                .setOrderId(123)
                .beginPayDialog();

//        final String orderUrl = "你的生成订单的API";
//        final WeakHashMap<String, Object> orderParams = new WeakHashMap<>();
//        //加入你的参数
//        RestClient.builder()
//                .url(orderUrl)
//                .loader(getContext())
//                .params(orderParams)
//                .success(new ISuccess() {
//                    @Override
//                    public void onSuccess(String response) {
//                        //进行具体的支付
//                        EcLogger.d("ORDER", response);
//                        final int orderId = JSON.parseObject(response).getInteger("result");
//                        FastPay.create(ShopCartDelegate.this)
//                                .setPayResultListener(ShopCartDelegate.this)
//                                .setOrderId(orderId)
//                                .beginPayDialog();
//                    }
//                })
//                .build()
//                .post();
    }

    private void updateTotalPrice(double subPrice) {
        double totalPrice = mAdapter.getTotalPrice();
        if (totalPrice > subPrice) {
            mTotalPrice = totalPrice - subPrice;
        } else {
            mTotalPrice = 0;
        }
        mAdapter.updateTotalPrice(mTotalPrice);
        mTvTotalPrice.setText(String.valueOf(mTotalPrice));
    }

    @SuppressWarnings("RestrictedApi")
    private void checkItemCount() {
        final int count = mAdapter.getItemCount();
        if (count == 0) {
            if (stubView == null) {
                stubView = mStubNoItem.inflate();
                stubView.setVisibility(View.VISIBLE);
                final AppCompatTextView tvToBuy = stubView.findViewById(R.id.tv_stub_to_buy);
                tvToBuy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(), "你该购物啦！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            mRecyclerView.setVisibility(View.GONE);
        } else {
            if (stubView != null) {
                stubView.setVisibility(View.GONE);
            }
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_shop_cart;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        mIconSelectAll.setTag(0);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        RestClient.builder()
                .url("shop_cart.php")
                .loader(getContext())
                .success(this)
                .build()
                .get();
    }

    @Override
    public void onSuccess(String response) {
        final ArrayList<MultipleItemEntity> data =
                new ShopCartDataConverter().setJsonData(response).convert();
        mAdapter = new ShopCartAdapter(data);
        mAdapter.setCartItemListener(this);

        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);

        updateTotalPrice(0);
        checkItemCount();
    }

    // +-商品数量时回调
    @Override
    public void onCountChangeBtnClick() {
        final double price = mAdapter.getTotalPrice();
        mTvTotalPrice.setText(String.valueOf(price));
    }

    @Override
    public void onCheckBtnClick() {
        final double price = mAdapter.getTotalPrice();
        mTvTotalPrice.setText(String.valueOf(price));

    }

    @Override
    public void onCheckAll() {
        // 全部选中
        if (mAdapter.getCheckCount() == mAdapter.getItemCount()){
            mIconSelectAll.setTextColor(ContextCompat.getColor(getContext(), R.color.app_main));
            mIconSelectAll.setTag(1);
        } else {
            mIconSelectAll.setTextColor(Color.GRAY);
            mIconSelectAll.setTag(0);
        }
    }

    @Override
    public void onPaySuccess() {

    }

    @Override
    public void onPaying() {

    }

    @Override
    public void onPayFail() {

    }

    @Override
    public void onPayCancel() {

    }

    @Override
    public void onPayConnectError() {

    }
}
